package com.lapis17.stock.service.impl;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lapis17.stock.mapper.*;
import com.lapis17.stock.pojo.domain.*;
import com.lapis17.stock.pojo.vo.StockInfoConfig;
import com.lapis17.stock.service.StockService;
import com.lapis17.stock.utils.DateTimeUtil;
import com.lapis17.stock.vo.resp.PageResult;
import com.lapis17.stock.vo.resp.R;
import com.lapis17.stock.vo.resp.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

@Slf4j
@Service
public class StockServiceImpl implements StockService {
    @Autowired
    private StockInfoConfig stockInfoConfig;
    @Autowired
    private StockOuterMarketIndexInfoMapper stockOuterMarketIndexInfoMapper;

    @Autowired
    private StockBlockRtInfoMapper blockRtInfoMapper;

    @Autowired
    private  StockRtInfoMapper stockRtInfoMapper;
    @Autowired
    private StockMarketIndexInfoMapper stockMarketIndexInfoMapper;
    @Autowired
    private StockBusinessMapper stockBusinessMapper;

    @Override
    public R<List<InnerMarketDomain>> getStockInfo() {

        //获取当前时间

        Date date = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();

        date = DateTime.parse("2021-12-28 09:31:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        //获取大盘代码
        List<String> innerStocks = stockInfoConfig.getInner();

        //获取数据并返回
        List<InnerMarketDomain>  stockRtInfoList = stockOuterMarketIndexInfoMapper.getStockInfo(date,innerStocks);

        return R.ok(stockRtInfoList);
    }

    @Override
    public R<List<StockBlockDomain>> getStockBlock() {


        Date date = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        //2021-12-21 09:30:00
        date = DateTime.parse("2021-12-21 09:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<StockBlockDomain> stockBlockDomainList =  blockRtInfoMapper.getStockBlock(date);

        return R.ok(stockBlockDomainList);
    }

    @Override
    public R<PageResult<StockUpdownDomain>> stockInfoByPage(Integer page, Integer pageSize) {


        Date date = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        //2021-12-21 09:30:00
        date = DateTime.parse("2021-12-30 09:32:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<StockUpdownDomain> stockUpdownDomainList = stockRtInfoMapper.getStockByTime(date);

        PageHelper.startPage(page,pageSize);
        PageInfo pageInfo = new PageInfo<>(stockUpdownDomainList);
        PageResult<StockUpdownDomain> pageResultPageResult = new PageResult(pageInfo);
        return  R.ok(pageResultPageResult);
    }

    @Override
    public R<List<StockUpdownDomain>> getIncrease() {
        Date date = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        //2021-12-21 09:30:00
        date = DateTime.parse("2021-12-30 09:32:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
         List<StockUpdownDomain>  stockUpdownDomainList = stockRtInfoMapper.getStockInfoIncreaseByTime(date);

        return R.ok(stockUpdownDomainList);
    }

    @Override
    public R<Map<String, List>> stockInfoUpDownCount() {
        //截至时间
        DateTime dateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());


        dateTime = DateTime.parse("2022-1-06 13:32:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        Date endDate = dateTime.toDate();
        //开盘时间
        DateTime Date = DateTimeUtil.getOpenDate(dateTime);
        Date openDate = Date.toDate();
        //获取涨停
        List<Map>  upList =   stockRtInfoMapper.getUpDownCount(openDate,endDate,1);

        //获取涨跌
        List<Map>  downList =   stockRtInfoMapper.getUpDownCount(openDate,endDate,0);

        Map<String,List>  hashMap = new HashMap<>();
        hashMap.put("upList",upList);
        hashMap.put("downList",downList);

        return R.ok(hashMap);
    }

    public void exportStockUpDownInfo(Integer page, Integer pageSize, HttpServletResponse httpServletResponse) {
        //获取股票涨跌停信息

        List<StockUpdownDomain> rows = this.stockInfoByPage(page, pageSize).getData().getRows();

        //导出为数据表格
        httpServletResponse.setContentType("application/vnd.ms-excel");
        //2.设置响应数据的编码格式
        httpServletResponse.setCharacterEncoding("utf-8");
        //3.设置默认的文件名称
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        try {
            String fileName = URLEncoder.encode("股票信息表", "UTF-8");
            //设置默认文件名称：兼容一些特殊浏览器
            httpServletResponse.setHeader("content-disposition", "attachment;filename=" + fileName + ".xls");
            //4.响应excel流
            EasyExcel
                    .write(httpServletResponse.getOutputStream(),StockUpdownDomain.class)
                    .sheet("股票信息")
                    .doWrite(rows);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("当前导出数据异常，当前页：{},每页大小：{},异常信息：{}",page,pageSize,e.getMessage());
        }

    }

    @Override
    public R<Map<String, List>> getStockComparedTradeAmt() {

        //获取T日的最新交易时间
        DateTime tEndDateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());

        tEndDateTime = DateTime.parse("2021-12-29 09:44:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));

        Date tEndDate = tEndDateTime.toDate();

        //获取T日的开盘时间
        DateTime tStartDateTime = DateTimeUtil.getOpenDate(tEndDateTime);
        Date tStartDate = tStartDateTime.toDate();

        List<Map>  tDate =  stockMarketIndexInfoMapper.getComparedStockTraAmout(tStartDate,tEndDate, stockInfoConfig.getInner());




        //获取T-1的最新交易时间
        DateTime tPreEndDateTime = DateTimeUtil.getPreviousTradingDay(tEndDateTime);
        Date tPreEndDate = tPreEndDateTime.toDate();


        //获取T-1日的开盘时间点
        DateTime tPreStartDateTime = DateTimeUtil.getOpenDate(tPreEndDateTime);
        Date tPreStartDate = tPreStartDateTime.toDate();
        List<Map>   tPreDate =  stockMarketIndexInfoMapper.getComparedStockTraAmout(tPreStartDate,tPreEndDate,stockInfoConfig.getInner());

        //组装数据
        Map<String,List> data  = new HashMap<>();
        data.put("amtList",tDate);
        data.put("yesAmtList",tPreDate);
        return R.ok(data);
    }

    @Override
    public R<Map> getStockInfoCount() {
        //获取当前最新交易时间
        DateTime curDateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        curDateTime = DateTime.parse("2021-12-30 09:32:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        Date curDate = curDateTime.toDate();

        //获取个股的区间统计数据
        List<Map> date =  stockRtInfoMapper.getStockRtUpDownCount(curDate);


        //组装数据
        Map<String,Object> result = new HashMap<>();
        result.put("time",curDate);
        result.put("infos",date);

        return R.ok(result);
    }

    @Override
    public R<List<Stock4MinuteDomain>> stockScreenTimeSharing(String code) {
        DateTime dateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        dateTime= DateTime.parse("2021-12-30 14:47:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        Date endTime = dateTime.toDate();
        Date startTime =DateTimeUtil.getOpenDate(dateTime).toDate();
        List<Stock4MinuteDomain> list=stockRtInfoMapper.getStockInfoByCodeAndDate(code,startTime,endTime);
        //判断非空处理
        if (CollectionUtils.isEmpty(list)) {
            list=new ArrayList<>();
        }
        //3.返回响应数据
        return R.ok(list);
    }

    @Override
    public R<StockSecondDetailDomain> stockScreenSecondDetail(String code) {
        DateTime dateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        dateTime= DateTime.parse("2021-12-30 14:47:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        Date curTime = dateTime.toDate();
        StockSecondDetailDomain res=stockRtInfoMapper.getStockScreenSecondDetail(code,curTime);
        //判断非空处理
        if (res==null) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        //3.返回响应数据
        return R.ok(res);
    }

    @Override
    public R<List<Stock4EvrDayDomain>> stockCreenDkLine(String stockCode) {
        DateTime dateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        dateTime= DateTime.parse("2021-12-30 14:47:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        Date endTime = dateTime.toDate();
        Date startTime =dateTime.minusDays(10).toDate();
        //2.调用mapper接口获取查询的集合信息-方案1
        //List<Stock4EvrDayDomain> data= stockRtInfoMapper.getStockInfo4EvrDay(stockCode,startTime,endTime);
        // 分步实现
        List<Date> times = stockRtInfoMapper.getLatestTime(stockCode, startTime, endTime);
        List<Stock4EvrDayDomain> data = stockRtInfoMapper.getStockInfo4EvrDayBlock(stockCode, times);
        //3.组装数据，响应
        return R.ok(data);
    }

    @Override
    public R<List<Stock4EvrWeekDomain>> stockCreenWkLine(String stockCode) {
        DateTime dateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        Date endTime = dateTime.toDate();
        Date startTime =dateTime.minusYears(5).toDate();
        //2.调用mapper接口获取查询的集合信息-方案1
        List<Stock4EvrWeekDomain> data= stockRtInfoMapper.getStockInfo4EvrWeek(stockCode,startTime,endTime);
        //3.组装数据，响应
        return R.ok(data);
    }

    @Override
    public R<List<Map>> stockSearchObscure(String searchStr) {
        Date currentTime = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
//            currentTime = DateTime.parse("2021-12-19 09:47:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<Map> resList =stockBusinessMapper.stockSearchObscure(searchStr.toCharArray());
        if (CollectionUtils.isEmpty(resList)) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        return R.ok(resList);
    }

    @Override
    public R<List<StockScreenSecondDomain>> stockScreenSecond(String code) {
        //2.调用mapper接口获取查询的集合信息-方案1
        List<StockScreenSecondDomain> res= stockRtInfoMapper.getstockScreenSecond(code);
        //3.组装数据，响应
        if (CollectionUtils.isEmpty(res)) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        return R.ok(res);
    }

    @Override
    public R<stockBusinessDomain> stockDescribe(String code) {
        stockBusinessDomain res=stockBusinessMapper.getStockDescribe(code);
        if(res==null){
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        return R.ok(res);
    }
}
